package com.coolrui.domain.dubbo.utils;

import com.coolrui.api.dto.UserDTO;
import com.coolrui.common.utils.MockDataUtils;
import com.coolrui.domain.user.entity.UserAccount;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * User实体属性转换
 */
@Mapper(componentModel = "spring") // 让 MapStruct 生成的实现类成为 Spring Bean
public abstract class UserConvertUtil {
    @Autowired
    private MockDataUtils mockDataUtils;

    /**
     * 将 User 实体转换为 UserDTO
     */
    @Mapping(target = "gender", source = "gender", qualifiedByName = "genderToString")
    @Mapping(target = "cityName", source = "cityId", qualifiedByName = "cityIdToCityName")
    @Mapping(target = "createTime", source = "createTime", qualifiedByName = "dateToString")
    @Mapping(target = "updateTime", source = "updateTime", qualifiedByName = "dateToString")
    @Mapping(target = "totalBalance", source = "totalBalance", qualifiedByName = "bigDecimalToString")
    @Mapping(target = "availableBalance", source = "availableBalance", qualifiedByName = "bigDecimalToString")
    @Mapping(target = "frozenBalance", source = "frozenBalance", qualifiedByName = "bigDecimalToString")
    public abstract UserDTO toUserDTO(UserAccount user);

    public abstract List<UserDTO> toUserDTO(List<UserAccount> userList);
    //=========================================自定义转换方法=====================================
    @Named("genderToString")
    public String genderToString(Integer gender){
        switch (gender) {
            case 1: return "男";
            case 2: return "女";
            default: return "未知";
        }
    }

    /**
     * 自定义方法：将 cityId 转为 cityName
     */
    @Named("cityIdToCityName")
    public String cityIdToCityName(Integer cityId) {
        return mockDataUtils.getCityName(cityId);
    }

    // BigDecimal 转 String
    @Named("bigDecimalToString")
    public String bigDecimalToString(BigDecimal value) {
        return value != null ? value.toPlainString() : null;
    }

    /**
     * 自定义方法：将 Date 转为格式化字符串
     */
    @Named("dateToString")
    public String dateToString(Date date) {
        if (date == null) return null;
        String format = "yyyy-MM-dd HH:mm:ss";
        return DateFormatUtils.format(date, format);
    }
}
